<template>
  <el-dialog
    v-model="visible"
    title="订单详情"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="order-detail-content" v-if="orderDetail">
      <!-- 订单基本信息 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <h3>订单信息</h3>
            <el-tag :type="getStatusType(orderDetail.orderStatus)" size="large">
              {{ getStatusText(orderDetail.orderStatus) }}
            </el-tag>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="label">订单号：</span>
              <span class="value">{{ orderDetail.orderNumber }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">下单时间：</span>
              <span class="value">{{ formatDateTime(orderDetail.createdAt) }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">支付方式：</span>
              <span class="value">{{ getPaymentMethodText(orderDetail.paymentMethod) }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">最后更新：</span>
              <span class="value">{{ formatDateTime(orderDetail.updatedAt) }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>
      
      <!-- 寄件人信息 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <h3>
              <el-icon><User /></el-icon>
              寄件人信息
            </h3>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="label">姓名：</span>
              <span class="value">{{ orderDetail.senderName }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">电话：</span>
              <span class="value">
                <el-link type="primary" @click="callPhone(orderDetail.senderPhone)">
                  {{ orderDetail.senderPhone }}
                </el-link>
              </span>
            </div>
          </el-col>
          <el-col :span="24">
            <div class="info-item">
              <span class="label">地址：</span>
              <span class="value">{{ orderDetail.senderAddress }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>
      
      <!-- 收件人信息 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <h3>
              <el-icon><LocationFilled /></el-icon>
              收件人信息
            </h3>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="label">姓名：</span>
              <span class="value">{{ orderDetail.receiverName }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">电话：</span>
              <span class="value">
                <el-link type="primary" @click="callPhone(orderDetail.receiverPhone)">
                  {{ orderDetail.receiverPhone }}
                </el-link>
              </span>
            </div>
          </el-col>
          <el-col :span="24">
            <div class="info-item">
              <span class="label">地址：</span>
              <span class="value">{{ orderDetail.receiverAddress }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>
      
      <!-- 物品信息 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <h3>
              <el-icon><Box /></el-icon>
              物品信息
            </h3>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">物品类型：</span>
              <span class="value">{{ getItemTypeText(orderDetail.itemType) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">重量：</span>
              <span class="value">{{ orderDetail.itemWeight }}kg</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">体积：</span>
              <span class="value">{{ orderDetail.itemVolume }}m³</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">保价金额：</span>
              <span class="value">¥{{ orderDetail.insuredValue }}</span>
            </div>
          </el-col>
        </el-row>
        
        <div class="info-item" v-if="orderDetail.remark">
          <span class="label">备注：</span>
          <div class="remark-content">{{ orderDetail.remark }}</div>
        </div>
      </el-card>
      
      <!-- 费用信息 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <div class="card-header">
            <h3>
              <el-icon><Money /></el-icon>
              费用明细
            </h3>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="label">基础费用：</span>
              <span class="value">¥{{ orderDetail.baseFee }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">重量费用：</span>
              <span class="value">¥{{ orderDetail.weightFee }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">服务费用：</span>
              <span class="value">¥{{ orderDetail.serviceFee }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">保险费用：</span>
              <span class="value">¥{{ orderDetail.insuranceFee }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-divider />
        
        <div class="total-fee">
          <span class="label">总费用：</span>
          <span class="value total">¥{{ orderDetail.totalFee }}</span>
        </div>
      </el-card>
    </div>
    
    <!-- 加载状态 -->
    <div class="loading-state" v-if="loading">
      <el-skeleton :rows="8" animated />
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button 
          v-if="showStartDeliveryBtn" 
          type="primary" 
          @click="handleStartDelivery"
        >
          开始发货
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { User, LocationFilled, Box, Money } from '@element-plus/icons-vue'
import { courierApi, type AvailableOrder } from '@/api/courier'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

interface Props {
  visible: boolean
  orderId?: number
  showStartDeliveryBtn?: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'start-delivery', orderId: number): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  showStartDeliveryBtn: false
})

const emit = defineEmits<Emits>()
const router = useRouter()

const orderDetail = ref<AvailableOrder | null>(null)
const loading = ref(false)

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 监听对话框显示状态
watch(() => props.visible, (newVal) => {
  if (newVal && props.orderId) {
    fetchOrderDetail()
  }
})

// 获取订单详情
const fetchOrderDetail = async () => {
  if (!props.orderId) return
  
  loading.value = true
  try {
    console.log('获取订单详情, ID:', props.orderId)
    const response = await courierApi.getOrderDetails(props.orderId)
    
    if (response.code === 200) {
      orderDetail.value = response.data
      console.log('订单详情:', orderDetail.value)
    } else {
      ElMessage.error(response.message || '获取订单详情失败')
    }
  } catch (error: any) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  orderDetail.value = null
}

// 开始发货
const handleStartDelivery = () => {
  if (orderDetail.value) {
    // 跳转到配送管理页面，携带订单ID参数
    router.push({
      path: '/delivery-management',
      query: {
        orderId: orderDetail.value.deliveryOrderId.toString()
      }
    })
    handleClose()
  }
}

// 拨打电话
const callPhone = (phone: string) => {
  window.open(`tel:${phone}`)
}

// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap: { [key: number]: string } = {
    0: '待揽收',
    1: '待发货',
    2: '运输中',
    3: '待签收',
    4: '已完成'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态标签类型
const getStatusType = (status: number) => {
  const typeMap: { [key: number]: string } = {
    0: 'danger',
    1: 'warning',
    2: 'primary',
    3: 'info',
    4: 'success'
  }
  return typeMap[status] || 'default'
}

// 获取支付方式文本
const getPaymentMethodText = (method: string) => {
  const methodMap: { [key: string]: string } = {
    'online': '在线支付',
    'cash': '货到付款',
    'card': '银行卡支付',
    'alipay': '支付宝',
    'wechat': '微信支付'
  }
  return methodMap[method] || method
}

// 获取物品类型文本
const getItemTypeText = (itemType: string) => {
  const typeMap: { [key: string]: string } = {
    'electronics': '电子产品',
    'clothes': '服装',
    'food': '食品',
    'books': '书籍',
    'documents': '文件',
    'fragile': '易碎品',
    'other': '其他'
  }
  return typeMap[itemType] || itemType
}

// 格式化时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}
</script>

<style scoped>
.order-detail-content {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-card {
  margin-bottom: 16px;
}

.detail-card:last-child {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0;
}

.card-header h3 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
}

.info-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
  font-size: 14px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  min-width: 80px;
  color: #666;
  font-weight: 500;
}

.value {
  flex: 1;
  color: #333;
  word-break: break-all;
}

.remark-content {
  background: #f8f9fa;
  padding: 8px 12px;
  border-radius: 4px;
  border-left: 3px solid #409eff;
  margin-top: 4px;
  line-height: 1.5;
}

.total-fee {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  padding: 12px 0;
}

.total-fee .value.total {
  font-size: 20px;
  color: #e74c3c;
}

.loading-state {
  padding: 20px;
}

@media (max-width: 768px) {
  .el-dialog {
    width: 95% !important;
    margin: 5vh auto;
  }
  
  .order-detail-content {
    max-height: 60vh;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .label {
    min-width: auto;
    margin-bottom: 4px;
  }
}
</style> 